package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

@Component
public class IssueUserPondTask {

    private static Log logger = LogFactory.getLog(IssueUserPondTask.class);

    @Resource
    private UserDao userDao;

    @Resource
    private ChatterFactorDao chatterFactorDao;

    @Resource
    private ChatterLevelDao chatterLevelDao;

    @Resource
    private ChatterWorkSettingDao chatterWorkSettingDao;

    @Resource
    private UserWlmDao userWlmDao;

    @Resource
    private UserChatterMappingDao userChatterMappingDao;

    @Resource
    private IssueUserPoolDao issueUserPoolDao;

    @Resource
    private UserHomePageRecordDao userHomePageRecordDao;

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();

    @NacosValue(value = "${issue.pond.task.switch:false}", autoRefreshed = true)
    private boolean issuePondTaskSwitch;

    @Scheduled(fixedDelay = 150000)
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============IssueUserPondTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        if (!issuePondTaskSwitch) {
            logger.info("=============IssueUserPondTask任务关闭");
            return;
        }

        //计算公式：Profile初始权重【Q】*在班状态【M】*在线状态【N】*上限约束【Y】+随机参数【Z】+区间跨越参数【P】+最高优先级参数【α】

        try {
            //model
            List<UserEntity> userEntityList = userDao.getAllModels();

            double weightValue = 0;
            double workValue = 0;
            double OnlineValue = 0;
            double connectionValue = 0;
            double randomValue = 0;
            double intervalValue = 0;
            double firstValue = 0;
            //1 有model的chatter
            //2 空model
            //3 素人
            int chatterUserType = 1;
            for (UserEntity userEntity : userEntityList) {

                if(userEntity.getUserCode().equals("298049006397970666")){
                    int a=1;
                }
                //1 有model的全职chatter
                //2 有model的兼职头部chatter
                //3 有model的兼职腰部chatter
                //4 有model的兼职尾部chatter
                //5 空model
                //6 素人
                //7 有model的新chatter

                //当为cm
                Integer chatterType = 1;
                if (userEntity.getUserType() == 2) {
                    chatterUserType = 1;
                    UserEntity chatterInfo = userDao.getChatterInfo(userEntity.getUserCode());
                    if (chatterInfo != null) {
                        chatterType = getChatterType(chatterInfo, chatterUserType);
                        weightValue = getWeightValue(userEntity, chatterInfo, chatterUserType, chatterType);
                        workValue = getWorkValue(userEntity, chatterInfo, chatterUserType, chatterType);
                        OnlineValue = getOnlineValue(userEntity, chatterInfo, chatterUserType, chatterType);
                        connectionValue = getConnectionValue(userEntity, chatterInfo, chatterUserType, chatterType);
                        randomValue = getRandomValue(userEntity, chatterInfo, chatterUserType, chatterType);
                        intervalValue = getIntervalValue(userEntity, chatterInfo, chatterUserType, chatterType);
                        firstValue = getFirstValue(userEntity, chatterInfo, chatterUserType, chatterType);
                    }
                } else {
                    //m
                    chatterUserType = 2;
                    chatterType = getChatterType(null, chatterUserType);
                    weightValue = getWeightValue(userEntity, null, chatterUserType, chatterType);
                    workValue = getWorkValue(userEntity, null, chatterUserType, chatterType);
                    OnlineValue = getOnlineValue(userEntity, null, chatterUserType, chatterType);
                    connectionValue = getConnectionValue(userEntity, null, chatterUserType, chatterType);
                    randomValue = getRandomValue(userEntity, null, chatterUserType, chatterType);
                    intervalValue = getIntervalValue(userEntity, null, chatterUserType, chatterType);
                    firstValue = getFirstValue(userEntity, null, chatterUserType, chatterType);
                }
                double pp = (weightValue * workValue * OnlineValue * connectionValue) + randomValue + intervalValue + firstValue;

                IssueUserPoolEntity issueUserPoolEntity = new IssueUserPoolEntity();
                int poolNum = 1;
                if (chatterUserType == 1) {
                    if (chatterType == 7) {
                        poolNum = 2;
                    }
                } else {
                    poolNum = 3;
                }
                issueUserPoolEntity.setPoolNum(poolNum);
                issueUserPoolEntity.setUserCode(userEntity.getUserCode());
                issueUserPoolEntity.setUserType(chatterType);
                issueUserPoolEntity.setGender(userEntity.getGender());
                issueUserPoolEntity.setOnline(userEntity.getOnline());
                issueUserPoolEntity.setParamNum(pp);
                issueUserPoolEntity.setUseStatus(0);
                issueUserPoolDao.insert(issueUserPoolEntity);
            }

            //读取在线素人
            List<UserEntity> normalUserList = userDao.getNormalUser();
            for (UserEntity userEntity : normalUserList) {
                chatterUserType = 3;
                Integer chatterType = getChatterType(null, chatterUserType);
                weightValue = getWeightValue(userEntity, null, chatterUserType, chatterType);
                workValue = getWorkValue(userEntity, null, chatterUserType, chatterType);
                OnlineValue = getOnlineValue(userEntity, null, chatterUserType, chatterType);
                connectionValue = getConnectionValue(userEntity, null, chatterUserType, chatterType);
                randomValue = getRandomValue(userEntity, null, chatterUserType, chatterType);
                intervalValue = getIntervalValue(userEntity, null, chatterUserType, chatterType);
                firstValue = getFirstValue(userEntity, null, chatterUserType, chatterType);
                double pp = (weightValue * workValue * OnlineValue * connectionValue) + randomValue + intervalValue + firstValue;

                IssueUserPoolEntity issueUserPoolEntity = new IssueUserPoolEntity();
                issueUserPoolEntity.setPoolNum(4);
                issueUserPoolEntity.setUserCode(userEntity.getUserCode());
                issueUserPoolEntity.setUserType(chatterType);
                issueUserPoolEntity.setGender(userEntity.getGender());
                issueUserPoolEntity.setOnline(userEntity.getOnline());
                issueUserPoolEntity.setParamNum(pp);
                issueUserPoolEntity.setUseStatus(0);
                issueUserPoolDao.insert(issueUserPoolEntity);
            }

            if (!(userEntityList.isEmpty() && normalUserList.isEmpty())) {
                //删除所有状态为1的数据
                issueUserPoolDao.deleteNotUse();
                //更新状态为1
                issueUserPoolDao.updateUseStatus();
            }
        } catch (Exception e) {
            logger.error("issueUserPoolError", e);
        }

        //查询出所有的chatter
        //chatter下所有的model
        //读取配置表取值
        //保存或更新
    }

    private Integer getChatterType(UserEntity chatterInfo, int chatterUserType) {
        int chatterType = 1;
        if (chatterUserType == 1) {
            //工作类型：1-全职 2-兼职
            if (chatterInfo.getWorkType() != null && chatterInfo.getWorkType() != 1) {
                //2 有model的兼职头部chatter
                //3 有model的兼职腰部chatter
                //4 有model的兼职尾部chatter
                //7 有model的新chatter
                if (newChatter(chatterInfo.getGmtCreate())) {
                    chatterType = 7;
                } else {
                    ChatterLevelEntity chatterLevelEntity = chatterLevelDao.getChatterLevel(chatterInfo.getUserCode());
                    if (chatterLevelEntity != null) {
                        //1有model的兼职头部chatter  2有model的兼职腰部chatter 3有model的兼职尾部chatter
                        chatterType = chatterLevelEntity.getLevel() + 1;
                    }
                }
            }
        } else if (chatterUserType == 2) {
            chatterType = 5;
        } else {
            chatterType = 6;
        }
        return chatterType;
    }


    //Profile初始权重【Q】

    private double getWeightValue(UserEntity userEntity, UserEntity chatterInfo, int chatterUserType, Integer chatterType) {
        double result = 0;

        ChatterFactorEntity chatterFactorEntity = chatterFactorDao.getFactorValue(1, 1, chatterType);
        return chatterFactorEntity != null ? chatterFactorEntity.getFactorValue() : result;
    }


    //在班状态【M】
    private double getWorkValue(UserEntity userEntity, UserEntity chatterInfo, int chatterUserType, Integer chatterType) {
        double result = 0;

        //1 在班系数
        //2 非在班系数

        int factorType = 1;
        if (chatterUserType == 1) {
            //判断是否在班
            factorType = 2;
            ChatterWorkSettingEntity chatterWorkSettingEntity = chatterWorkSettingDao.getChatterWorkSetting(chatterInfo.getUserCode());
            if (chatterWorkSettingEntity != null) {
                int hour = LocalTime.now().getHour();
                if (chatterWorkSettingEntity.getStartHour() <= hour && hour < chatterWorkSettingEntity.getEndHour()) {
                    factorType = 1;
                } else if (chatterWorkSettingEntity.getStartHour2() <= hour && hour < chatterWorkSettingEntity.getEndHour2()) {
                    factorType = 1;
                }
            }
        }
        ChatterFactorEntity chatterFactorEntity = chatterFactorDao.getFactorValue(2, factorType, chatterType);
        return chatterFactorEntity != null ? chatterFactorEntity.getFactorValue() : result;
    }


    //在线状态【N】
    private double getOnlineValue(UserEntity userEntity, UserEntity chatterInfo, int chatterUserType, Integer chatterType) {
        double result = 0;

        //1 在线系数
        //2 刚刚在线系数
        //3 最近在线系数
        //4 其他系数

        int factorType = 4;
        Date onlineDate = new Date(Long.parseLong(userEntity.getOnlineTimestamp()));
        long diffSeconds = ((new Date()).getTime() - onlineDate.getTime()) / 1000;
        if (diffSeconds > 0 && diffSeconds < 121) {
            factorType = 1;
        } else if (diffSeconds > 120 && diffSeconds < 601) {
            factorType = 2;
        } else if (diffSeconds > 600 && diffSeconds < 3601) {
            factorType = 3;
        }
        ChatterFactorEntity chatterFactorEntity = chatterFactorDao.getFactorValue(3, factorType, chatterType);

        return chatterFactorEntity != null ? chatterFactorEntity.getFactorValue() : result;
    }

    //上限约束【Y】
    private double getConnectionValue(UserEntity userEntity, UserEntity chatterInfo, int chatterUserType, Integer chatterType) {
        double result = 0;

        //1 15分钟达到上限系数
        //2 当日达到上限系数
        //3 均未达到上限系数
        //4 15分钟达到上限个数
        //5 当日达到上限个数
        int factorType = 1;
        ChatterFactorEntity chatterFactorEntity = chatterFactorDao.getFactorValue(4, 4, chatterType);
        int minuteCount = 3;
        if (chatterFactorEntity != null && chatterFactorEntity.getFactorValue() != null) {
            double factorValue = chatterFactorEntity.getFactorValue();
            minuteCount = (int) factorValue;
        }

        chatterFactorEntity = chatterFactorDao.getFactorValue(4, 5, chatterType);
        int dayCount = 80;
        if (chatterFactorEntity != null && chatterFactorEntity.getFactorValue() != null) {
            double factorValue = chatterFactorEntity.getFactorValue();
            dayCount = (int) factorValue;
        }

        List<String> modelList = new ArrayList<>();
        if (chatterUserType == 1) {
            List<String> list = userChatterMappingDao.selectAll(chatterInfo.getUserCode());
            modelList.addAll(list);
        } else {
            modelList.add(userEntity.getUserCode());
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, 15 * -1);

        int connectionCount = userWlmDao.getConnectionCount(modelList, calendar.getTime());

        if (connectionCount < minuteCount) {
            LocalDate today = LocalDate.now();
            LocalDateTime startOfDay = LocalDateTime.of(today, LocalTime.MIN);
            Date date = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            int dayConnectionCount = userWlmDao.getConnectionCount(modelList, date);
            if (dayConnectionCount >= dayCount) {
                factorType = 2;
            } else {
                factorType = 3;
            }
        }
        chatterFactorEntity = chatterFactorDao.getFactorValue(4, factorType, chatterType);
        return chatterFactorEntity != null ? chatterFactorEntity.getFactorValue() : result;
    }

    //随机参数【Z】
    private double getRandomValue(UserEntity userEntity, UserEntity chatterInfo, int chatterUserType, Integer chatterType) {
        double result = 0;
        Random random = new Random();
        int randomNumber = random.nextInt(10000) + 1;
        result = (double) randomNumber / 10000000;
        return result;
    }


    //区间跨越参数【P】
    private double getIntervalValue(UserEntity userEntity, UserEntity chatterInfo, int chatterUserType, Integer chatterType) {
        double result = 0;

        ChatterFactorEntity chatterFactorEntity = chatterFactorDao.getFactorValue(5, 1, chatterType);
        return chatterFactorEntity != null ? chatterFactorEntity.getFactorValue() : result;
    }


    //最高优先级参数【α】
    private double getFirstValue(UserEntity userEntity, UserEntity chatterInfo, int chatterUserType, Integer chatterType) {
        double result = 0;
        ChatterFactorEntity chatterFactorEntity = null;
        if (chatterType == 6) {
            int likeCount = userHomePageRecordDao.getLikeCount(userEntity.getUserCode(), 1);
            if (likeCount > 0) {
                chatterFactorEntity = chatterFactorDao.getFactorValue(6, 1, chatterType);
            }
        }
        return chatterFactorEntity != null ? chatterFactorEntity.getFactorValue() : result;
    }

    private Boolean newChatter(Date createDate) {
        boolean result = true;
        Date currentDate = new Date();
        // 使用Calendar类添加14天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(createDate);
        calendar.add(Calendar.DATE, 14);
        // 获取14天后的日期
        Date fourteenDaysLater = calendar.getTime();
        if (currentDate.after(fourteenDaysLater)) {
            result = false;
        }
        return result;
    }


}
